package com.lin.java.tool.send.email;

import com.lin.java.tool.send.enums.SendEnum;
import com.lin.java.tool.send.ex.CustomSendException;
import com.lin.java.tool.send.factory.EmailFactory;
import com.lin.java.tool.send.model.dto.EmailDTO;
import com.lin.java.tool.send.model.EmailTemplate;
import com.lin.java.tool.send.utils.TemplateParser;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Map;

/**
 * @author: linjiang
 * @date: 2025/1/20
 */
public class CommonEmailStrategy extends EmailStrategy {

    public CommonEmailStrategy(EmailFactory factory, InitializeEmailTemplate initializeEmailTemplate) {
        super(factory, initializeEmailTemplate);
    }

    @Override
    protected void sendEmail(EmailTemplate template, EmailDTO send) {
        // 替换模板内容
        String content = replaceTemplateContent(template.getContent(), send.getVariables());

        // 创建邮件发送对象
        JavaMailSender sender = factory.getEmailSender();
        MimeMessage mimeMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setSubject(template.getSubject());
            helper.setFrom(send.getFrom());
            helper.setTo(send.getEmails().toArray(new String[0]));
            helper.setText(content);
            helper.setSentDate(new Date());

            // 附件
            EmailDTO.Attachment attachment = send.getAttachment();
            if (attachment != null) {
                InputStreamSource inpt = new InputStreamResource(attachment.getInputStream());
                helper.addAttachment(attachment.getFilename(), inpt);
            }

            sender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
            throw new CustomSendException(SendEnum.SEND_FAIl.getCode(), "邮件发送失败！");
        }
    }

    /**
     * 替换模板内容
     *
     * @param content
     * @param variables
     * @return
     */
    private String replaceTemplateContent(String content, Map<String, Object> variables) {
        return new TemplateParser(variables).parse(content);
    }

}
